package com.dzu.gulimall.cart.interceptor;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import com.dzu.common.constant.AuthServerConstant;
import com.dzu.common.constant.CartConstant;
import com.dzu.common.vo.MemberResponseVo;
import com.dzu.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author ZhaoDong
 * @date 2022/7/2 14:29
 * @description gulimall
 * 在执行目标方法之前，判断用户的登陆状态。并封装传递给controller目标请求
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<UserInfoTo> THREAD_LOCAL = new ThreadLocal<>();



    /**
     * 目标执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo memberResponseVo = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberResponseVo != null) {
            // 用户登录
            userInfoTo.setUserId(memberResponseVo.getId());
        }

        Cookie[] cookies = request.getCookies();

        if (ArrayUtil.isNotEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                // user-key
                if (cookie.getName().equalsIgnoreCase(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(Boolean.TRUE);

                }
            }
        }

        // 如果没有临时用户，一定要分配一个临时用户
        if (!userInfoTo.getTempUser()) {
            UUID uuid = UUID.fastUUID();
            userInfoTo.setUserKey(uuid.toString());
        }

        // 目标方法执行之前
        THREAD_LOCAL.set(userInfoTo);

        return Boolean.TRUE;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = THREAD_LOCAL.get();

        // 如果没有临时用户，一定保存一个临时用户
        if (!userInfoTo.getTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());

            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIME_OUT);

            response.addCookie(cookie);

        }

    }
}
